package com.tsxy.mall.controller;

import com.tsxy.mall.entity.User;
import com.tsxy.mall.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/toLogin")
    public String toLogin(){
        return "/login";
    }

    @PostMapping("/login")
    public String login(String username,String password, HttpSession session){
        try {
            User user = new User(null,username, password,null);
            User result = userService.login(user);
            session.setAttribute("user", result);
            return "redirect:/";
        } catch (Exception e) {
            session.setAttribute("msg", e.getMessage());
            return "/login";
        }
    }
    @GetMapping("/logout")
    public String exit(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }
    //跳转到注册页面
    @GetMapping("/toReg")
    public String toreg(){
        return "reg";
    }
    /*
    用户注册
     */
   @PostMapping("/toReg")
    public String reg(User user, String repassword, Model model){
        //获取参数
        //调用service层
        int result = userService.reg(user, repassword);
        //返回数据、获取页面
        if (result > 0){
            //注册成功
            //跳转到登录页面
            return "redirect:login";
        }else{
            //传递错误信息
            String error ="位置错误,请联系管理员";
            if (result == -1){
                error = "账号格式不正确";
            }else if(result == -2){
                error = "密码格式不正确";
            }else if (result == -3){
                error= "两次密码不一致";
            }else if (result == -4){
                error =  "账号不可用";
            }else if (result == -5){
                error = "密码不能为空";
            }
            model.addAttribute("error",error);
            //跳转注册页面    请求转发
            return "reg";
        }
    }
}
